export const useIntegralStore = defineStore('integral', () => {

  // 订单优惠券显示文字描述
  let couponText: any = $ref('暂无可用优惠券')
  const updateCouponText = (payload) => {
    couponText = payload
  }
  // 订单优惠券列表
  let orderCouponList: any = $ref([])
  const updateCouponList = (payload) => {
    orderCouponList = payload
  }

  // 当前选择的是哪张优惠券
  let currentSelectCoupon: any = $ref({})
  const updateCurrenSelectCouopon = (payload) => {
    currentSelectCoupon = payload
  }

  // 不使用优惠最初始的金额
  let initTotalAmount: any = $ref(0)
  const updateInitTotalAmount = (payload) => {
    initTotalAmount = payload
    updateFinallyAmount()
  }

  // 初始优惠金额
  let initDiscountAmount: any = $ref(0)
  const updateInitDiscountAmount = (payload) => {
    initDiscountAmount = payload
    updateFinallyAmount()
  }

  // 积分优惠数额
  let pointAmount: any = $ref(0)
  const updatePointAmount = (payload) => {
    pointAmount = payload
    updateFinallyAmount()
  }

  // 优惠券优惠数额
  let couponAmount: any = $ref(0)
  const updateCouponAmount = (payload) => {
    couponAmount = payload
    updateFinallyAmount()
  }

  // 总计优惠数额
  let finallyDiscountAmount: any = $ref(0)
  // 最终需要支付的金额
  let finallyPayAmount: any = $ref(0)
  const updateFinallyAmount = () => {
    finallyDiscountAmount = (Number(initDiscountAmount) + Number(pointAmount) + Number(couponAmount)).toFixed(2)
    finallyPayAmount = (Number(initTotalAmount) - Number(pointAmount) - Number(couponAmount)).toFixed(2)
  }

  // 最终选择的优惠券
  let selectCoupon: any = $ref({})
  const updateSelectCoupon = (payload) => {
    selectCoupon = payload
  }

  // 重置置空
  const handleInitBlank = () => {
    couponText = '暂无可用优惠券'
    updateCouponList([])
    updateCurrenSelectCouopon({})
    updateInitTotalAmount(0)
    updateInitDiscountAmount(0)
    updatePointAmount(0)
    updateCouponAmount(0)
    updateSelectCoupon({})
    // finallyDiscountAmount = initDiscountAmount
    // finallyPayAmount = initTotalAmount
  }
  return {
    couponText: $$(couponText),
    orderCouponList: $$(orderCouponList),
    currentSelectCoupon: $$(currentSelectCoupon),
    finallyDiscountAmount: $$(finallyDiscountAmount),
    pointAmount: $$(pointAmount),
    couponAmount: $$(couponAmount),
    initTotalAmount: $$(initTotalAmount),
    finallyPayAmount: $$(finallyPayAmount),
    initDiscountAmount: $$(initDiscountAmount),
    selectCoupon: $$(selectCoupon),
    updateCouponText,
    updateCouponList,
    updateCurrenSelectCouopon,
    updateFinallyAmount,
    updatePointAmount,
    updateCouponAmount,
    updateInitTotalAmount,
    updateInitDiscountAmount,
    handleInitBlank,
    updateSelectCoupon,
  }
}, { unistorage: { key: 'config-integral' } })

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useIntegralStore, import.meta.hot))
